package net.kqinfo.core.controller;

import net.kqinfo.core.Constants;
import net.kqinfo.core.shiro.IncorrectCaptchaException;
import net.kqinfo.core.shiro.ShiroDbRealm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.core.Controller;
import com.jfinal.ext.render.DwzRender;

public class LoginController extends Controller{
	
	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class); 
	
	private static final String LOGINPAGE = "/WEB-INF/views/login.html";

	public void index(){
		render(LOGINPAGE);
	}
	
	public void loginDialog(){
		render(new DwzRender("会话超时，请重新登录。", "main", "ajax"));
	}
	
	public void timeout(){
		render(new DwzRender("会话超时，请重新登录。", "main", "ajax"));
	}
	
	public void timeoutsuccess(){
		Subject subject = SecurityUtils.getSubject();
		ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser)subject.getPrincipal();

		setSessionAttr(Constants.LOGIN_USER, shiroUser.getUser());
		redirect("/");
	}
	
	public void fail(){
		String msg = parseException();
		setAttr("msg", msg);
		setAttr("username", getAttr(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM));
		render(LOGINPAGE);
	}
	
	private String parseException() {
		String errorString = getAttr(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		Class<?> error = null;
		try {
			if (errorString != null) {
				error = Class.forName(errorString);
			}
		} catch (ClassNotFoundException e) {
			LOG.error(e.getMessage());
		} 
		
		String msg = "其他错误！";
		if (error != null) {
			if (error.equals(UnknownAccountException.class))
				msg = "未知帐号错误！";
			else if (error.equals(IncorrectCredentialsException.class))
				msg = "密码错误！";
			else if (error.equals(IncorrectCaptchaException.class))
				msg = "验证码错误！";
			else if (error.equals(AuthenticationException.class))
				msg = "认证失败！";
			else if (error.equals(DisabledAccountException.class))
				msg = "账号被冻结！";
		}
		return "登录失败，" + msg;
	}
}
